<script setup>
import { watch } from 'vue'
import { ref } from 'vue'
import { useCartStore } from '@/stores/cart.js'
defineOptions({
  name: 'togGoodNum'
})
const cartStore = useCartStore()
const props = defineProps(['num', 'stock', 'sel_num', 'id'])
const emit = defineEmits(['togNum'])
const num = props.sel_num ? ref(props.sel_num) : ref(props.num)
watch(num, (newVal) => {
  if (newVal > props.stock) num.value = props.stock
  if (newVal < 1) num.value = 1
  if (props.sel_num) cartStore.togNum(props.id, newVal)
  else emit('togNum', newVal)
})
</script>

<template>
  <div>
    <button @click="num--" :disabled="num <= 1">
      <van-icon name="minus" />
    </button>
    <input type="number" v-model="num" />
    <button @click="num++" :disabled="num >= props.stock">
      <van-icon name="plus" />
    </button>
  </div>
</template>

<style scoped lang="scss">
div {
  button {
    width: 28px;
    height: 28px;
    border: 0px;
    color: black;
    &:active {
      color: gray;
    }
  }
  input {
    width: 32px;
    height: 28px;
    border: 0;
    text-align: center;
    font-weight: bold;
    background-color: transparent;
  }
}
</style>
